package com.hj.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hj.dao.ScoreMapper;
import com.hj.pojo.Score;
import com.hj.pojo.ScoreExample;
import com.hj.pojo.ScoreExample.Criteria;
import com.hj.pojo.Student;
import com.hj.service.IScoreService;
import com.hj.service.IStudentService;

@Service
public class ScoreServiceImpl implements IScoreService {

	@Autowired
	ScoreMapper scoreMapper;
	@Autowired
	IStudentService studentService;
	
	
	@Override
	public PageInfo<Score> list(Integer page, Integer size, Score score) {
		// TODO Auto-generated method stub
		PageHelper.startPage(page, size);
		return new PageInfo<Score>(scoreMapper.selectByExample(null));
	}

	@Transactional
	@Override
	public void add(Score score) {
		
		// 1 增加分数记录
		scoreMapper.insertSelective(score);
		
		// 2 修改学生pjf字段
		Student student = studentService.findOne(score.getsId());
		
		// 第一种实现，增加mapper方法（sql）
//		BigDecimal avg = scoreMapper.selectStudentAvg(score.getsId());
//		student.setPjf(avg);
		
		ScoreExample scEx = new ScoreExample();
		Criteria criteria = scEx.createCriteria();
		criteria.andSIdEqualTo(score.getsId());
		// 第二种实现
		List<Score> list = scoreMapper.selectByExample(scEx );
		Integer total = 0;
		for (Score s : list) {
			total += s.getsScore();
		}
		
//		Optional<Integer> totalOpt = list.stream().map( (s) -> { return s.getsScore();} ).reduce( (x, y) -> { return x + y;} );
//		totalOpt.get();
		
		// total / list.size();
		BigDecimal totalBig = new BigDecimal(total);
		BigDecimal avg = totalBig.divide(new BigDecimal(list.size()), 2, RoundingMode.HALF_UP);
		student.setPjf(avg);
		
		studentService.update(student);
		
	}

	@Override
	public void delete(String id) {

	}

	@Override
	public void update(Score score) {
		// TODO Auto-generated method stub

	}

	@Override
	public Score findOne(String id) {
		// TODO Auto-generated method stub
		return null;
	}

}
